﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Documents;
using zjx.Wpf.Graffitiboard.Adorners;

namespace zjx.Wpf.Graffitiboard.Core
{
    internal class SelectionService
    {
        private Graffitiboard multiTouchCanvas;

        private List<ISelectable> currentSelection;
        internal List<ISelectable> CurrentSelection
        {
            get
            {
                if (currentSelection == null)
                    currentSelection = new List<ISelectable>();

                return currentSelection;
            }
        }

        public SelectionService(Graffitiboard canvas)
        {
            this.multiTouchCanvas = canvas;
        }

        internal void SelectItem(ISelectable item)
        {
            this.ClearSelection();
            this.AddToSelection(item);
        }

        internal void AddToSelection(ISelectable item)
        {
            if (item.IsSelected == false)
            {
                item.IsSelected = true;
                CurrentSelection.Add(item);
                this.AddAdorner(item);
            }
        }

        private void AddAdorner(ISelectable item)
        {
            if (item.SelectionAdorner == null)
            {
                AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this.multiTouchCanvas);
                if (adornerLayer != null)
                {
                    item.SelectionAdorner = new ResizeRotateAdorner(this.multiTouchCanvas, item);
                    adornerLayer.Add(item.SelectionAdorner);
                }
            }
        }

        internal void RemoveFromSelection(ISelectable item)
        {
            if (item.IsSelected)
            {
                item.IsSelected = false;
                CurrentSelection.Remove(item);
                this.RemoveAdorner(item);
            }
        }

        private void RemoveAdorner(ISelectable item)
        {
            if (item.SelectionAdorner != null)
            {
                AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(this.multiTouchCanvas);
                if (adornerLayer != null)
                {
                    adornerLayer.Remove(item.SelectionAdorner);
                    item.SelectionAdorner = null;
                }
            }
        }

        internal void ClearSelection()
        {
            while (CurrentSelection.Count > 0)
            {
                this.RemoveFromSelection(CurrentSelection[0]);
            }
        }

        internal void SelectAll()
        {
            ClearSelection();
            foreach (var item in multiTouchCanvas.Children.OfType<ISelectable>())
            {
                this.AddToSelection(item);
            }
        }
    }
}
